import { ElMessage } from "element-plus";
let _debounceTimeout = null,
  _throttleRunning = false;
// 防抖
const debounce = (fn, delay = 500) => {
  clearTimeout(_debounceTimeout);
  _debounceTimeout = setTimeout(() => {
    fn();
  }, delay);
};

// 节流
const throttle = (fn, delay = 500) => {
  if (_throttleRunning) {
    return;
  }
  _throttleRunning = true;
  fn();
  setTimeout(() => {
    _throttleRunning = false;
  }, delay);
};
// Toast
const message = (title = "", type = "warning", param = {}) => {
  if (!title) return;
  ElMessage({
    message: title,
    type: type,
  });
};
//时间转化
// times  时间
// type  类型
// timestamp  是否时间戳
const timeFormat = (time, formattype = "YYYY-MM-DD hh:mm:ss", istimestamp) => {
  if (time === null || time === undefined || time === "") {
    return "格式转换失败(请传入有效的时间)";
  }
  let timestamp;
  if (typeof time === "number" || typeof time === "string") {
    timestamp = String(time);
  } else {
    return "格式转换失败(请传入有效的时间)";
  }
  if (istimestamp && timestamp.length < 13) {
    const numTimestamp = Number(timestamp);
    if (!isNaN(numTimestamp)) {
      timestamp = numTimestamp * Math.pow(10, 13 - timestamp.length);
    } else {
      return "格式转换失败(无效的时间戳)";
    }
  }
  const date = new Date(timestamp);
  if (isNaN(date.getTime())) {
    return "格式转换失败(无效的时间)";
  }
  const year = date.getFullYear();
  const month = ("0" + (date.getMonth() + 1)).slice(-2);
  const day = ("0" + date.getDate()).slice(-2);
  const hours = ("0" + date.getHours()).slice(-2);
  const minutes = ("0" + date.getMinutes()).slice(-2);
  const seconds = ("0" + date.getSeconds()).slice(-2);
  const formatresult = formattype
    .replace("YYYY", year)
    .replace("MM", month)
    .replace("DD", day)
    .replace("hh", hours)
    .replace("mm", minutes)
    .replace("ss", seconds);
  return formatresult || "格式转换失败(请传入规范的时间)";
};
export default {
  debounce,
  throttle,
  message,
  timeFormat,
};
